import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store'
import router from '@/router'

// 创建axios副本
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})

// 请求拦截
_axios.interceptors.request.use(
  config => {
    // 判断接口请求是否需要请求头
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    // console.log('响应错误', [error])
    // 错误统一处理
    if (error.response.data && error.response.data.message) {
      Toast.fail(error.response.data.message)
    }
    if (error.response.status === 401) {
      // 删除token
      store.commit('user/setToken', '')
      // 返回登录页,哪里来的退到哪去
      router.push('/login?redirect=' + router.currentRoute.fullPath)
    }
    return Promise.reject(error)
  }
)

export default _axios
